package cn.tedu.lbs.marketing.web.service;

import cn.tedu.lbs.basic.api.BasicApi;
import cn.tedu.lbs.marketing.web.repository.ActivityRepository;
import cn.tedu.lbs.marketing.web.util.AuthenticationContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.attach.dto.AttachDTO;
import com.tarena.lbs.pojo.attach.param.PicUpdateParam;
import com.tarena.lbs.pojo.attach.query.AttachQuery;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.marketing.param.ActivityParam;
import com.tarena.lbs.pojo.marketing.po.ActivityPO;
import com.tarena.lbs.pojo.marketing.query.ActivityQuery;
import com.tarena.lbs.pojo.marketing.vo.ActivityVO;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityService {
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private BasicApi basicApi;
    @DubboReference
    private AttachApi attachApi;
    public PageResult<ActivityVO> pageList(ActivityQuery query) throws BusinessException {
        //1.查询某个商家下的活动列表,先检查并且获取商家id
        Integer businessId = checkAndGetBusinessId();
        //2.利用businessId 可以查询活动的pos列表
        List<ActivityPO> pos= getActivitiesByBusinessId(businessId);
        //3.组织一个PageResult
        PageResult<ActivityVO> pageResult=new PageResult<>(10,1);
        pageResult.setTotal(100L);
        if (pos!=null&&pos.size()>0){
            pageResult.setObjects(pos.stream().map(po -> {
                ActivityVO vo = new ActivityVO();
                BeanUtils.copyProperties(po, vo);
                return vo;
            }).collect(Collectors.toList()));
        }
        return pageResult;
    }

    private List<ActivityPO> getActivitiesByBusinessId(Integer businessId) {
        //搜索商家下的活动 select * from activty where business_id=?
        QueryWrapper<ActivityPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("business_id",businessId);
        return activityRepository.list(queryWrapper);
    }

    private Integer checkAndGetBusinessId() throws BusinessException {
        //1.拿到认证对象
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        //2.断言空
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        //3.拿到角色
        Roles role = userPrinciple.getRole();
        Integer businessId=null;
        //4.如果角色是SHOP 需要给businessId赋值
        if (role==Roles.SHOP){
            businessId=getAdminBusinessId(userPrinciple.getId());
            Asserts.isTrue
                    (businessId==null,new BusinessException("-2","登录用户根本不存在"));
        }
        return businessId;
    }

    private Integer getAdminBusinessId(Integer id) throws BusinessException {
        AdminDTO adminDTO = basicApi.getAdminDetail(id);
        Asserts.isTrue(adminDTO==null,new BusinessException("-2","商家账号根本不存在"));
        return adminDTO.getBusinessId();
    }

    public void save(ActivityParam param) throws BusinessException {
        //1.检查 获取businessId
        Integer businessId = checkAndGetBusinessId();
        //2.封装po 写入数据库 获取返回id
        Integer id=saveActivity(businessId,param);
        //3.调用图片服务 绑定图片 bizType=100 营业执照 bizType=200 商家logo bizType=300 店铺门店
        //bizType=400 店铺logo bizType=500 文章封面 bizType=600 文章主题 bizType=700 活动
        bindPicture(param,id,700);
    }

    private void bindPicture(ActivityParam param, Integer bizId, Integer bizType) {
        //图片绑定 逻辑: 绑定几张图片,每张图片绑定 需要图片信息(id,fileUuid) bizId bizType
        String[] imgIds = param.getImgIds().split(",");//189,190,191
        //通过流api 将imgIds转化成 远程绑定图片的入参 PicUpdateParam
        if (imgIds!=null&&imgIds.length>0){
            List<PicUpdateParam> collect = Arrays.stream(imgIds).map(imgId -> {
                PicUpdateParam picParam = new PicUpdateParam();
                picParam.setId(Integer.valueOf(imgId));
                picParam.setBusinessId(bizId);
                picParam.setBusinessType(bizType);
                return picParam;
            }).collect(Collectors.toList());
            attachApi.batchUpdateBusiness(collect);
        }
    }

    private Integer saveActivity(Integer businessId, ActivityParam param) throws BusinessException {
        //1.将入参拷贝po
        ActivityPO poParam=new ActivityPO();
        BeanUtils.copyProperties(param,poParam);
        //2.补充属性 businessId status业务状态0待开始 1已开始 2已结束 enableStatus管理状态 0启用 1禁用
        //时间值 create update 活动开始以及结束时间 活动奖励0 优惠券 1积分 2 实物 3其他
        poParam.setBusinessId(businessId);
        poParam.setStatus(0);
        poParam.setEnableStatus(0);
        poParam.setCreateAt(new java.util.Date());
        poParam.setUpdateAt(new java.util.Date());
        poParam.setRewardType(0);
        try{
            poParam.setStartDate(DateUtils.parseDate(param.getStartDate(),"yyyy-MM-dd HH:mm:ss"));
            poParam.setEndDate(DateUtils.parseDate(param.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
        }catch (Exception e){
            throw new BusinessException("-2","活动开始和结束时间封装失败");
        }
        activityRepository.save(poParam);
        return poParam.getId();
    }

    public boolean isTargetCustmer(Integer userId, Integer activityId) throws BusinessException {
        //1.检查活动 是否存在 如果不存在 一定不可见 如果存在拿到目标人群targetCustmer
        ActivityPO po = activityRepository.getById(activityId);
        Asserts.isTrue(po==null,new BusinessException("-2","活动不存在"));
        //从非空的活动中 获取目标人群id 和 当前活动所属商家
        Integer businessId = po.getBusinessId();
        Integer targetCustomerId=Integer.valueOf(po.getTargetCustomer());
        //2.调用basic服务 查询该用户,在当前商家活动下 符合的人群有哪些List<Integer>
        List<Integer> userGroups=basicApi.getUserGroupIds(userId,businessId);
        //3.根据basic的反馈结果,判断是否展示
        if (userGroups!=null&&userGroups.size()>0){
            //用户 能够通过basic查到所属人群 目标人群是否在所属人群范围内 就是返回结果
            return userGroups.contains(targetCustomerId);
        }
        return false;
    }

    public ActivityVO detail(Integer id) throws BusinessException {
        //1.使用活动id查询活动的数据po
        ActivityPO po = activityRepository.getById(id);
        Asserts.isTrue(po==null,new BusinessException("-2","活动不存在"));
        //2.活动数据库表格 没有存储记录图片连接url 需要手动拼接url 远程调用图片服务查询图片  fileUuid
        List<String> imgUrls=getActivityImgUrls(id,700);//利用当初绑定图片的业务数据 bizId==活动id bizType=700
        //3.封装组织vo返回
        ActivityVO vo=new ActivityVO();
        BeanUtils.copyProperties(po,vo);
        vo.setImgPics(imgUrls);
        return vo;
    }
    @Value("${url.prefix}")
    private String urlPrefix;
    private List<String> getActivityImgUrls(Integer bizId,Integer bizType) {
        //设计接口 attach落地接口实现 marketing 调用接口方法 完善
        AttachQuery query=new AttachQuery();
        query.setBusinessId(bizId);
        query.setBusinessType(bizType);
        List<AttachDTO> dtos = attachApi.getAttachInfoByParam(query);
        //解析映射转化每个图片dto 变成图片url 把图片对象fileUuid 拼接url前缀
        if (dtos!=null&&dtos.size()>0){
            return dtos.stream().map(dto->{
                //在拼接url前缀的时候 要考虑 多环境下 url域名 端口 路径可能发生变化的
                return urlPrefix+dto.getFileUuid();
            }).collect(Collectors.toList());
        }
        return null;
    }

    public List<ActivityPO> getAvailableActivities(Integer storeId) {
        //1.在店铺绑定范围
        //2.状态待开始
        //3.奖励类型是0 优惠券
        //4.自动营销 1 开启
        //select * from activity where shop_ids=? and status=0 and reward_type=0 and marketing_type=1
        QueryWrapper<ActivityPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("shop_ids",storeId);
        queryWrapper.eq("status",0);//待开始状态
        queryWrapper.eq("reward_type",0);//优惠券
        queryWrapper.eq("marketing_type",1);//支持 开启自动营销
        return activityRepository.list(queryWrapper);

    }
}
